package com.hnly.djdl.model

import android.content.Context
import android.content.SharedPreferences
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.json.JSONArray

object RecordTools {
    private val _lines: MutableStateFlow<List<Snack>> = MutableStateFlow(listOf())
    val lines: StateFlow<List<Snack>> get() = _lines
    private var isInit = false
    private const val SP_KEY = "SNACKS"
    private const val KEY = "SNACKS"
    private fun getSp(context: Context): SharedPreferences? {
        return context.getSharedPreferences(SP_KEY, Context.MODE_PRIVATE)
    }

    private fun parseJSON(json: String): List<Snack> {
        if (json.isBlank()) {
            return listOf()
        }
        val jsonArray = JSONArray(json)
        val list = mutableListOf<Snack>()
        for (i in 0 until jsonArray.length()) {
            val jo = jsonArray.getJSONObject(i)
            val parseJSONObject = Snack().parseJSONObject(jo)
            list.add(parseJSONObject)
        }
        return list
    }

    private fun toJSON(listSearchResults: List<Snack>): String {
        val jsonArray = JSONArray()
        for (listSearchResult in listSearchResults) {
            jsonArray.put(listSearchResult.toJSONObject())
        }
        return jsonArray.toString()
    }

    fun checkInit(context: Context) {
        if (isInit.not()) {
            val str: String? = getSp(context = context)?.getString(KEY, null)
            if (str == null) {
                _lines.value = firstRecords
            } else {
                _lines.value = parseJSON(str)
            }
            isInit = true
        }
    }

    fun add(context: Context, sr: Snack) {
        val arrayListOf: ArrayList<Snack> = arrayListOf()
        arrayListOf.add(sr)
        arrayListOf.addAll(_lines.value)
        if (arrayListOf.size > 30) {
            arrayListOf.removeLast()
        }
        _lines.value = arrayListOf
        val json = toJSON(_lines.value)
        getSp(context = context)?.edit()?.putString(KEY, json)?.apply()
    }
}

private val firstRecords by lazy {
    mutableListOf<Snack>().apply {
        add(P4.p11)
        add(P4.p12)
        add(P4.p13)
        add(P4.p14)
        add(P4.p15)
        add(P4.p16)
    }
}